// const sha1 = require('sha1')
const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt')

const UserModel = require('../models/users')
const checkNotLogin = require('../middlewares/check').checkNotLogin

// GET /signin 登录页
router.get('/', checkNotLogin, (req, res, next) => {
  res.render('user/signin')
})

// POST /signin 用户登录
router.post('/', checkNotLogin, (req, res, next) => {
  const name = req.fields.name
  const password = req.fields.password

  // 校验参数
  try {
    if (!name.length) {
      throw new Error('请填写用户名')
    }
    if (!password.length) {
      throw new Error('请填写密码')
    }
  } catch (e) {
    req.flash('error', e.message)
    return res.redirect('back')
  }

  UserModel.getUserByName(name)
    .then((user) => {
      if (!user) {
        req.flash('error', '用户不存在')
        return res.redirect('back')
      }
      bcrypt.compare(password, user.password, (err, res) => {
        if (err) {
          console.log(err)
        }
        const pwdMatchFlag = res
        tryLogin(pwdMatchFlag)
      })

      // 尝试登录
      function tryLogin (pwdMatchFlag) {
        if (pwdMatchFlag) {
          req.flash('success', '登录成功')
          // 用户信息写入 session
          delete user.password
          req.session.user = user
          // 跳转到主页
          res.redirect('/')
        } else {
          req.flash('error', '用户名或密码错误')
          return res.redirect('back')
        }
      }
    })
    .catch(next)
})

module.exports = router
